package net.obviam.droidz;

import net.obiam.droidz.model.Helicopter;
import android.app.Activity;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.util.Log;

public class MainGamePanel extends SurfaceView implements
		SurfaceHolder.Callback {

	private MainThread thread;
	private static final String TAG = MainGamePanel.class.getSimpleName();
	private Helicopter helicopter;
	
	public MainGamePanel(Context context) {
		super(context);
		// adding the callback (this) to the surface holder to intercept events
		getHolder().addCallback(this);
		helicopter = new Helicopter(BitmapFactory.decodeResource(getResources(), R.drawable.droid_1), 50, 50);
		thread = new MainThread(getHolder(), this);
		// make the GamePanel focusable so it can handle events
		setFocusable(true);
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
	}

	public void surfaceCreated(SurfaceHolder holder) {
		thread.setRunning(true);
		thread.start();
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		Log.d(TAG, "Surface being destroyed");
		boolean retry = true;
		while(retry){
			try{
				thread.join();
				retry = false;
			}
			catch (InterruptedException e){
				
			}
		}
		Log.d(TAG, "Thread has shut down cleanly");
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		Log.d(TAG, "Motion: " + event.toString());
		if(event.getAction() == MotionEvent.ACTION_UP) {
			helicopter.setTouched(false);
			return true;
		}
		else{
			//If finger is held down or is moving, then we consider this an action and keep the helicopter moving
			helicopter.setTouched(true);
			//((Activity)getContext()).finish();
			Log.d(TAG, "Touched: x=" + event.getX() + ",y=" + event.getY());
		}
		return true;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		canvas.drawColor(Color.BLACK);
		helicopter.draw(canvas);
		helicopter.move();
	}
}
